import 'package:flutter/material.dart';
import 'package:gd_assistant/api/apiHandler.dart';
import 'package:gd_assistant/page/public/colors.dart';
import 'package:gd_assistant/page/public/publicView.dart';
import 'package:gd_assistant/page/public/themeUtils.dart';
import 'package:gd_assistant/page/user/selectArchivesPage.dart';
import 'package:gd_assistant/third/flutter_datetime_picker.dart';
import 'package:gd_assistant/util/RelativeDateFormat.dart';
import 'package:gd_assistant/model/healthRecordModel.dart';
import 'package:gd_assistant/globalConfig.dart';
import 'package:gd_assistant/util/customRoute.dart';
import 'package:gd_assistant/util/publicUtil.dart';
import 'package:image_pickers/image_pickers.dart';

class userArchivesPage extends StatefulWidget {
  userArchivesPage({Key key,this.userId="",this.orderId="", this.userName = "", this.healthRecord, this.callBack}):super(key: key);
  String userId;
  String orderId;
  String userName;
  HealthRecordModel healthRecord;
  Function callBack;
  @override
  _userArchivesPageState createState() => _userArchivesPageState();
}

class _userArchivesPageState extends State<userArchivesPage> {
  bool isDark = false;
  String userId = "";
  String orderId = "";
  TextEditingController name = TextEditingController();
  String checkTime = "";
  TextEditingController problem = TextEditingController(); 
  TextEditingController result = TextEditingController();
  TextEditingController medication = TextEditingController();
  TextEditingController other = TextEditingController();
  List<String> tags = [];
  List<String> images = [];

  //上传的图片数组
  List<String> urlImages = [];
  List<String> uploadImages = [];
  
  //上传图片
  uploadImage() async {

    List<String> result = await publicUtil.onUploadFiles(uploadImages);
    images = [];
    images.addAll(urlImages.map((v)=>v.substring(GlobalConfig.qiNiuUri.length)).toList());
    images.addAll(result);
    await setupArchive();
  }
  
  //提交档案结果
  setupArchive() async {
    dynamic cb;
    if (widget.healthRecord != null) {
       //修改
      cb = await apiHandler.updateCase(widget.healthRecord.sId, RelativeDateFormat.timeStampFormat(checkTime), tags, result.text, problem.text, medication.text, other.text, images);
    }else{
      //新增
      cb = await apiHandler.createNewCase(widget.userId, widget.orderId, RelativeDateFormat.timeStampFormat(checkTime), tags, result.text, problem.text, medication.text, other.text, images);
    }
    
    if (cb != null) {
      TostUtil.show("档案提交成功");
    }
    TostUtil.removeLoading(context);
    Navigator.pop(context);
    if (widget.callBack != null) {
      widget.callBack();
    }
  }


  @override
  void dispose() {
    super.dispose();
    name.dispose();
    problem.dispose();
    result.dispose();
    medication.dispose();
    other.dispose();
  }
  @override
  void initState() {
    super.initState();
    if (widget.userId != "" && widget.orderId != "") {
      userId = widget.userId;
      orderId = widget.orderId;
    }
    if (widget.healthRecord != null) {
      tags = widget.healthRecord.selectedReservations;
      checkTime = RelativeDateFormat.YMDformat(widget.healthRecord.checkTime);
      problem.text = widget.healthRecord.meProblem;
      result.text = widget.healthRecord.checkDetail;
      medication.text = widget.healthRecord.doctorSolution;
      other.text = widget.healthRecord.otherPoints;
      images = widget.healthRecord.checkImgs.map((v)=>GlobalConfig.qiNiuUri+v).toList();
    }else{

    }
    name.text = widget.userName;
    urlImages = images;
  }

  @override
  Widget build(BuildContext context) {
    isDark = ThemeUtils.isDark(context);
    //测试图片上传
    final EdgeInsets padding = MediaQuery.of(context).padding;
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.healthRecord != null ? "修改档案" : "新建档案"),
        elevation: 0
      ),
      body: Container(
        child: Column(
          children: <Widget>[
            Expanded(
              flex: 1,
              child: ListView(
                children: <Widget>[
                  ZLTextField(
                    title: "就诊人",
                    pliceHorder: "请输入就诊人名字",
                    controller: name,
                    isEdit: false,
                  ),
                  ZLSelectField(
                    title: "检查时间",
                    text: checkTime,
                    pliceHorder: "请选择检查日期",
                    onTap: () {
                       DatePicker.showDatePicker(context,
                        showTitleActions: true,
                        onConfirm: (date) {
                          checkTime = RelativeDateFormat.YMDformat(date.millisecondsSinceEpoch);
                          setState(() {});
                        }, locale: LocaleType.zh);
                    },
                  ),
                  ZLSelectField(
                    title: "检查项目",
                    text: "",
                    pliceHorder: tags.length > 0 ? "" : "请选择检查项目",
                    onTap: () {
                     Navigator.of(context).push(
                        CustomRoute(selectArchivesPage(selectTags: tags, selectedEnd: (selectedTags){
                          setState(() {
                            tags = selectedTags;
                          });
                        },))
                      );   
                    },
                  ),
                  ZLTagsView(
                    titles: tags,
                  ),
                  ZLTextView(
                    title: "主诉及存在问题",
                    pliceHorder: "请输入",
                    controller: problem,
                  ),
                  ZLTextView(
                    title: "检查结果",
                    pliceHorder: "请输入",
                    controller: result,
                  ),
                  ZLTextView(
                    title: "处理及用药",
                    pliceHorder: "请输入",
                    controller: medication,
                  ),
                  ZLTextView(
                    title: "其他注意事项",
                    pliceHorder: "请输入",
                    controller: other,
                  ),
                  ZLImageSelectView(
                    title: "上传资料和图片",
                    images: images,
                    onChange: (urlPaths, listImagePaths){
                      print(urlPaths);
                      print(listImagePaths);
                      urlImages = urlPaths;
                      List<String> up = [];
                      for (Media path in listImagePaths) {
                        up.add(path.path);
                      }
                      uploadImages = up;
                    },
                  )
                ],
              ),
            ),
           Container(
              padding: EdgeInsets.only(bottom: padding.bottom),
              width: double.infinity,
              height: 65 + padding.bottom,
              color: isDark ? Colours.dark_bg_color : Colors.white,
              child: ZLButton(
                  title: "完成",
                  onTap: checkTime != "" && tags.length > 0 ? (){
                    TostUtil.showLoading(context, "档案提交中...");
                    uploadImage();
                  } : null
                )
            ),
          ],
        )
      ),
    );
  }
}